package com.ktdaddy.exception;


import com.ktdaddy.enums.ErrorCode;
import com.ktdaddy.utils.ApiResponse;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author kdaddy@163.com
 * @date 2021/4/21 22:54
 */
@RestControllerAdvice
public class ExceptionController {

    @ExceptionHandler(ShiroException.class)
    public Object handleShiroException(ShiroException e) {
        ApiResponse response =
                ApiResponse.build(HttpStatus.UNAUTHORIZED.value(),
                        HttpStatus.UNAUTHORIZED.getReasonPhrase(),e.getMessage());
        return response;
    }

    @ExceptionHandler(BusinessRuntimeException.class)
    public Object handleBusinessRuntimeException(BusinessRuntimeException e){
        ApiResponse response = ApiResponse.build(e.getErrorCode(),e.getErrorMsg(),e);
        return response;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotSupportException(MethodArgumentNotValidException e){
        ApiResponse response = ApiResponse.build(ErrorCode.REQUEST_PARAM_ERROR.getErrorCode(),
                e.getBindingResult().getFieldError().getDefaultMessage(),
                e.getBindingResult().getFieldError());
        return response;
    }
}
